<template>
  <div class="ele-admin-loading">
    <i></i>
    <i></i>
    <i></i>
    <i></i>
  </div>
</template>
<script setup>
import {ref, onMounted} from 'vue';
import {jwtDecode} from "jwt-decode";
import {casAuth} from '@/api/auth.js';
import {EleMessage} from 'ele-admin-plus/es';
import {setToken} from '@/utils/token-util.js';
import {useRouter} from 'vue-router';

const CAS_USER_KEY = "CasUser";
const CAS_SERVER_URL = "https://uis.fdzcxy.edu.cn/cas";
const TICKET_JWT_ISS = 'https://uis.fdzcxy.edu.cn/cas';


const {push} = useRouter();


onMounted(() => {
  console.log("准备开始进行授权");
  // return;
  let ticket = getQueryString('ticket');
  console.log("当前获取到的ticket为", ticket);
  if (ticket) {
    //const secret = TICKET_JWT_SECRET;
    const iss = TICKET_JWT_ISS;
    const aud = location.origin + location.pathname;
    let result = {};
    try {
      // result = jwt.decode(ticket, secret, false, 'HS512');
      result = jwtDecode(ticket);//尝试直接进行解码ticket
      console.log('result is', result);
    } catch (e) {
      EleMessage.error('当前token已经失效，请关闭当前页面重新从i至诚进入');
      console.log(e);
      return;
    }
    //console.log("st decode", result);
    if (result.iss != iss) {
      console.log('iss error');
      //提示校验出错
      // window.localStorage.removeItem(CAS_USER_KEY);
    } else if (result.aud && result.aud.indexOf(aud) != 0) {
      console.log('aud error')
      //提示校验出错
      // window.localStorage.removeItem(CAS_USER_KEY);
    } else {
      // let casUser = {
      //   "service": result.aud,
      //   "ticket": result.jti,
      //   "user": result.sub,
      //   "exp": result.exp,
      //   "attributes": {
      //     "identityTypeCode": result.identityTypeCode,
      //     "organizationCode": result.organizationCode,
      //     "idToken": result.idToken,
      //   }
      // }
      // console.log("casUser", casUser);
      // this.casUser = casUser;
      // console.log("login success");
      // let date = new Date();
      // let year = date.getFullYear();
      // let month = formatNum(date.getMonth() + 1);
      // let day = formatNum(date.getDate());
      // let timeline = year + '' + month + '' + day;
      // let randomStr = randomString(16);
      // console.log(timeline + ',' + casUser.user + ',' + randomStr);
      // let userCode = casUser.user;
      // console.log('encrypt', userCode);
      let data = {};
      //加密后的用户账号
      data.code = result.sub;
      data.ticket = ticket;
      casAuth(data).then(res => {
        console.log("casAuth res is ", res);
        if (res.isUser) {
          setToken('Bearer ' + res.token, false);
          goHome();//进入首页
        } else {
          EleMessage.error(res.msg);
          push('/no/auth');
          return;
        }
      });
    }
  } else {
    //没有正确获取到ticket
    //这部分代码是有正常执行的
    // EleMessage.error("没有获取到正确的token，请关闭浏览器后重新打开再次尝试登入");
    // return;
    // console.log("redirect to cas login");
    const service = location.origin + location.pathname + location.hash;
    //console.log("service", service);
    //console.log("window.location.href", CAS_SERVER_URL + '/login' + '?service=' + encodeURIComponent(service));
    window.location.href = CAS_SERVER_URL + '/login' + '?service=' + encodeURIComponent(service);
  }
});

// const formatNum = (t) => {
//   if (t < 10) {
//     return "0" + t;
//   } else {
//     return t;
//   }
// }


// const randomString = (len) => {
//   len = len || 32;
//   let $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
//   /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
//   let maxPos = $chars.length;
//   let pwd = '';
//   for (let i = 0; i < len; i++) {
//     pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
//   }
//   return pwd;
// }


const getQueryString = (name) => {
  console.log("getQueryString", window.location.search)
  let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
  let r = window.location.search.substr(1).match(reg)
  console.log("getQueryString", name, r)
  if (r != null) {
    return unescape(r[2])
  }
  return null
}


/** 跳转到首页 */
const goHome = () => {
  push('/');
};
</script>


<style scoped>
body {
  width: 100%;
  height: 100%
}

.ele-admin-loading {
  width: 28px;
  height: 28px;
  display: grid;
  grid-gap: 8px;
  grid-template-rows: repeat(2, 1fr);
  grid-template-columns: repeat(2, 1fr);
  transform: rotate(45deg);
  animation: loadingRotate 1.2s infinite linear;
  position: fixed;
  top: calc(50% - 14px);
  left: calc(50% - 14px);
}

.ele-admin-loading > i {
  border-radius: 50%;
  background: #1677ff;
}

.ele-admin-loading > i:nth-child(2) {
  opacity: 0.7;
}

.ele-admin-loading > i:nth-child(3) {
  opacity: 0.5;
}

.ele-admin-loading > i:nth-child(4) {
  opacity: 0.3;
}
</style>



